package com.itqdkj.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itqdkj.health.constant.MessageConstant;
import com.itqdkj.health.constant.RedisMessageConstant;
import com.itqdkj.health.entity.Result;
import com.itqdkj.health.pojo.Order;
import com.itqdkj.health.service.OrderService;
import com.itqdkj.health.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * 体检预约
 */
@RestController
@RequestMapping("/order")
public class OrderMobileController {
    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 体验预约
     * @param map
     * @return
     */
    @RequestMapping("/submit")
    public Result submitOrder(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        //从Redis中获取缓存的验证码，key为手机号+ RedisMessageConstant.SENDTYPE_ORDER
        String codeInRedis = jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_ORDER);
        System.out.println("codeInRedis="+codeInRedis);
        String validateCode = (String) map.get("validateCode");
        System.out.println("validateCode="+validateCode);
        //校验手机验证码
         if(codeInRedis == null || !codeInRedis.equals(validateCode)){
             return new Result(false, MessageConstant.VALIDATECODE_ERROR);
         }

         //此时验证码没有问题，处理预约信息保存
         Result result = null;
        //调用体检预约服务
        try {
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            result = orderService.saveOrder(map);
            if(result.isFlag()){
                //预约成功，发送短信通知
                String orderDate = (String)map.get("orderDate");

                try {
                    SMSUtils.sendShortMessage(telephone,orderDate);
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            //预约失败
            return result;
        }
    }
    //订单详情页面，使用订单id，查询订单的详情
    @RequestMapping(value = "/findById")
    public Result submit(Integer id){
        Map<String,Object> map = orderService.findById(id);
         if(map !=null && map.size()>0){
             return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
         }else{
             return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
         }
    }
}
